package com.zzyl.nursing.service.impl;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.Constants;
import com.zzyl.framework.config.properties.AlertProperties;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-04
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }
    @Autowired
    private AlertProperties alertProperties;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private IAlertDataService alertDataService;
    /**
     * 报警规则过滤
     */
    @Override
    public void alertFilter() {
        //查询所有规则
        long count = this.count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        //判断是否为空
        if (count==0){
            return;
        }
        //查询所有设备上报的数据（在缓存中）
        List<String> deviceDataList = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        //判断数据是否为空
        if (CollectionUtil.isEmpty(deviceDataList)) {
            return;
        }
        List<DeviceData> deviceDatas=new ArrayList<>();
        //解析上报数据
        deviceDataList.forEach(deviceData -> {
            //这里的数据是json格式的字符串，
            List<DeviceData> list = JSONUtil.toList(JSONUtil.toJsonStr(deviceData), DeviceData.class);
            deviceDatas.addAll(list);

        });
        //数据报警处理
        deviceDatas.forEach(deviceData -> {
            alertFilter(deviceData);
        });
    }

    private void alertFilter(DeviceData deviceData) {
        //查询该产品物模型下的全部设备的规则
        List<AlertRule> alertRuleList = this.list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getProductKey, deviceData.getProductKey()));
        if (CollectionUtil.isEmpty(alertRuleList)){
            return;
        }
        //遍历每一条规则，并进行校验
        alertRuleList.forEach(alertRule -> {
            deviceDataAlarmHandle(alertRule,deviceData);
        });
    }

    private void deviceDataAlarmHandle(AlertRule alertRule, DeviceData deviceData) {
        //1.判断是否在生效时间内 00:00-23:59:00
        //1.1获取生效时间
        String period = alertRule.getAlertEffectivePeriod();
        String[] split = period.split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        LocalTime alarmTime = deviceData.getAlarmTime().toLocalTime();
        //2.检验数据是否达到阈值
        String iotId = deviceData.getIotId();
        //设置报警数量的key
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX+iotId+":"+deviceData.getFunctionId()+":"+alertRule.getId();
        if (alarmTime.isBefore(startTime) || alarmTime.isAfter(endTime)){
            //说明报警时间不在这个时间段内
            return;
        }
        //2.检验数据是否达到阈值
        //2.1 数据对比，上报的数据与规则中的阈值进行对比，规则中的，>=65或者<65 ,上报数据dataValue
        Long value = alertRule.getValue();
        Double dataValue = Double.valueOf(deviceData.getDataValue());
        int compare = NumberUtil.compare(dataValue, value);
        if ((alertRule.getOperator().equals("<")&&compare<0||alertRule.getOperator().equals(">=")&&compare>=0)){
            //满足条件，进行报警处理
            log.info("当前上报的数据符合规则异常");
        }else {
            log.info("当前上报的数据不符合规则异常");
            //正常数据，并删除redis报警数，然后直接返回
            redisTemplate.delete(aggCountKey);
            return;
        }
        //3.判断是否在沉默周期内
        String silentKey=CacheConstants.ALERT_SILENT_PREFIX+iotId+":"+deviceData.getFunctionId()+":"+alertRule.getId();
        String silentData = (String) redisTemplate.opsForValue().get(silentKey);
        if (StrUtil.isNotEmpty(silentData)){
            //说明在沉默期
            return;
        }
        //4.判断持续周期
        //4.1 查询报警次数
        String aggCountData = (String) redisTemplate.opsForValue().get(aggCountKey);
        //4.2 计算当前报警次数
        int count = StringUtils.isEmpty(aggCountData) ? 1 : Integer.parseInt(aggCountData) + 1;
        if (ObjectUtil.notEqual(alertRule.getDuration(), count)){
            //不等，则更新redis中的报警次数
            redisTemplate.opsForValue().set(aggCountKey, String.valueOf(count));
            return;
        }
        //校验全部通过，则进行报警处理
        //删除redis中的报警次数
        redisTemplate.delete(aggCountKey);
        //5.2 添加redis中的沉默周期
        redisTemplate.opsForValue().set(silentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        //5.3 发送报警数据，需要找到对应的人
        List<Long> userIds = new ArrayList<>();
        //5.3.1 如果是老人异常数据
        if (alertRule.getAlertDataType().equals(0)) {
            //如果是报警手表
            if (deviceData.getLocationType().equals(0)) {
                //通过老人id查找到对应的护理员列表
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            }else if (deviceData.getLocationType().equals(1) && deviceData.getPhysicalLocationType().equals(2)){
                //如果是床位设备的话，通过床位id找到老人，通过老人id找到对应的护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        }else{
            //5.3.2.如果是设备异常数据,找维修工或者行政人员
            userIds = userRoleMapper.selectUserIdByRoleName(alertProperties.getDeviceMaintainerRole());
        }
        //5.3.3 无论是哪种情况，都要通知超级管理员
        List<Long> managerIds = userRoleMapper.selectUserIdByRoleName(alertProperties.getManagerRole());
        //合并
        Collection<Long> allUserIds = CollUtil.addAll(userIds, managerIds);
        //去重
        allUserIds = CollUtil.distinct(allUserIds);

        //5.4 保存报警数据
        List<AlertData> alertDataList = insertAlertData(allUserIds, alertRule, deviceData);
        // websocket推送消息
        websocketNotity(alertDataList.get(0), alertRule,allUserIds);
    }
    private List<AlertData> insertAlertData(Collection<Long> allUserIds, AlertRule alertRule, DeviceData deviceData) {
        // 对象拷贝
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        // 心率<60,持续3个周期就报警
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);
        alertData.setType(alertRule.getAlertDataType());
        // 遍历allUserIds
        List<AlertData> list = allUserIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setId(null);
            return dbAlertData;
        }).collect(Collectors.toList());

        // 批量保存
        alertDataService.saveBatch(list);
        return list;
    }
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * websocket推送消息
     * @param alertData
     * @param rule
     * @param allUserIds
     */
    private void websocketNotity(AlertData alertData, AlertRule rule, Collection<Long> allUserIds) {

        // 属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(rule.getFunctionName());
        alertNotifyVo.setAlertDataType(rule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        // 向指定的人推送消息
        webSocketServer.sendMessageToConsumer(alertNotifyVo, allUserIds);

    }
}
